#改写jwt默认返回值
import re
from django.contrib.auth.backends import ModelBackend
from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.serializers import ModelSerializer

from apps.goods.models import GoodsVisitCount
from apps.users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id': user.id,
        'username': user.username
    }

class MeiduoModelBackend(ModelBackend):
    def authenticate(self,request,username=None, password=None, **kwargs):
        #后台登陆的不传入request,管理员
        if request is None:
            try:
                #去用户模型表中找
                user = User.objects.get(username=username,is_staff=True)
            except:
                return None
            #验证密码
            if user.check_password(password):
                return user

        #正常登陆用户
        else:
            try:
                if re.match(r'^1[3-9]\d{9}$', username):
                    user = User.objects.get(mobile=username)
                else:
                    user = User.objects.get(username=username)
                # user = User.objects.get(username=username)
            except:
                # 如果未查到数据，则返回None，用于后续判断
                try:
                    user = User.objects.get(mobile=username)
                except:
                    return None
                    # return None

            # 判断密码
            if user.check_password(password):
                return user
            else:
                return None

#分页类
class PageNum(PageNumberPagination):
    page_size = 5
    page_size_query_param = 'pagesize'
    max_page_size = 10

    #自定义了分页返回的结果
    def get_paginated_response(self, data):
        return Response({
            'count':self.page.paginator.count,
            'lists':data,
            'page':self.page.number,
            'pages':self.page.paginator.num_pages, #总页数
            'pagesize':self.page_size #页容量
        })





